home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 10 / AACD 10.iso / AACD / Online / SpeakFreely / src / common.c < prev    next >
C/C++ Source or Header  |  2000-05-18  |  1KB  |  57 lines

  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #include "common.h"
  7.  
  8. /*  StrReplace    -- Replace sequence OldStr with NewStr in Str.
  9.            Returns a newly allocated string with the sequence
  10.            replaced or NULL is the new string cannot be allocated.
  11.            If OldStr does not occur in Str, the input string Str
  12.            is returned.  */
  13.  
  14. char *StrReplace(Str, OldStr, NewStr)
  15.   char *Str;
  16.   char *OldStr;
  17.   char *NewStr;
  18. {
  19.     int OldLen, NewLen;
  20.     char *p, *q, *qq, *pp;
  21.     char *result;
  22.     int oc = 0;
  23.  
  24.     q = Str;
  25.     while ((q = strstr(q, OldStr)) != NULL) {
  26.     oc++;
  27.     q++;
  28.     }
  29.  
  30.     if (oc == 0) {
  31.     return Str;
  32.     }
  33.  
  34.     OldLen = strlen(OldStr);
  35.     NewLen = strlen(NewStr);
  36.  
  37.     result = (char *) malloc(strlen(Str) + (oc * (NewLen - OldLen)) + 1);
  38.  
  39.     if (result != NULL) {
  40.     qq = result;
  41.     q = Str;
  42.  
  43.     while ((p = strstr(q, OldStr)) != NULL) {
  44.         pp = qq + (p - q);
  45.         memcpy(qq, q, p - q);
  46.         memcpy(pp, NewStr, NewLen);
  47.         q = p + OldLen;
  48.         qq = pp + NewLen;
  49.     }
  50.  
  51.     memcpy(qq, q, strlen(Str) - (q - Str));
  52.  
  53.         *((qq + strlen(Str)) - (q - Str)) = '\0';
  54.     }
  55.     return result;
  56. }
  57.